<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <!-- 左侧显示总记录数 -->
        <span slot="before">共{{ page.total }}条记录</span>
        <!-- 右侧显示按钮 Excel表格导入 -->
        <template v-slot:after>
          <el-button type="warning" @click="$router.push('/import')">Excel表格导入</el-button>
          <el-button type="danger" @click="exportData">Excel表格导出</el-button>
          <el-button :disabled="!checkPermission('POINT-USER-ADD')" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table v-loading="loading" border :data="list">
          <!-- sortable 可排序的 -->
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="员工头像" style="width:100px">
            <template v-slot="obj">
              <img v-imageerror="require('@/assets/common/head.jpg')" :src="obj.row.staffPhoto" style="width:100px;height:100px" alt="暂无头像" @click="showQRCode(obj.row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" :formatter="formatEmployee" prop="formOfEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <!-- 作用域插槽+过滤器 处理时间 -->
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry"><template v-slot="obj">{{ dayjs(obj.row.timeOfEntry).format('YYYY-MM-DD hh:mm') }}</template></el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template v-slot="obj">
              <el-switch :value="obj.row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="obj">
              <el-button type="text" size="small" @click="$router.push(`employees/detail/${obj.row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(obj.row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployees(obj.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination :current-page="page.page" :page-size="page.size" :total="page.total" layout="prev, pager, next" @current-change="changePage" />
        </el-row>
      </el-card>
    </div>
    <!-- 放置弹层组件 -->
    <!-- .sync是子组件修改父组件的一个语法糖 -->
    <AddEmployee :show-dialog.sync="showDialog" />
    <el-dialog title="二维码" :visible="showCodeDialog" @close="showCodeDialog = false">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />

      </el-row></el-dialog>

    <!-- 分配权限组件 -->
    <AssignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'// 引入枚举文件
import AddEmployee from './components/addEmployee.vue'
import Qrcode from 'qrcode'
import AssignRole from './components/assign-role.vue'

export default {
  name: 'Employees',
  components: {
    AddEmployee, AssignRole
  },
  data() {
    return {
      list: [],
      page: {
        page: 1, // 当前页
        size: 10, // 每页数量
        total: 0 // 总数
      },
      loading: false, // 显示遮罩层
      showDialog: false,
      showCodeDialog: false, // 显示二维码弹层
      userId: null,
      showRoleDialog: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      this.loading = false
    },
    changePage(newPage) {
      console.log(11)
      this.page.page = newPage// 赋值最新页码
      this.getEmployeeList()// 获取新页面
    },
    /** 格式化聘用形式 */
    formatEmployee(row, column, callValue, index) {
      // 找1所对应的值
      const obj = EmployeeEnum.hireType.find((item) => {
        return item.id === callValue
      })
      return obj ? obj.value : '未知'
    },
    async delEmployees(id) {
      try {
        await this.$confirm('确定要删除该员工吗')
        // 点击了确定
        await delEmployee(id)
        this.$message.success('删除成功')
        this.getEmployeeList()// 获取新页面
      } catch (err) {
        console.log(err)
      }
    },
    exportData() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 导出excel
      import('@/vendor/Export2Excel').then(async excel => {
        //  excel是引入文件的导出对象
        // 现在没有接口可以获取所有的数据
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const data = this.formatJson(headers, rows)// 返回的data就是要导出的结果
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          multiHeader,
          merges
        })
      })
    },
    formatJson(headers, rows) {
      return rows.map((item) => {
        //  item是一个对象
        return Object.keys(headers).map((key) => {
          // 需要判断字段
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            // 格式化日期
            return this.dayjs(item[headers[key]]).format('YYYY-MM-DD')
          } else if (headers[key] === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
            return obj ? obj.value : '未知'
          }
          return item[headers[key]]
        })
      })
    }, showQRCode(url) {
      if (url) {
        this.showCodeDialog = true
        // 打开弹层时图片还没有渲染
        this.$nextTick(() => {
          Qrcode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        this.$message.warning('该用户暂无头像')
      }
    },
    async editRole(id) {
      this.userId = id // props传值 是异步的
      await this.$refs.assignRole.getUserDetailById(id) // 父组件调用子组件方法
      this.showRoleDialog = true
    }
  }
}
</script>

<style>

</style>

